<template>
    <a-config-provider :locale="locale" :theme="theme" :data-my-theme="systemHeme">
        <RouterView/>
    </a-config-provider>
</template>
<script>

import EventListener from "./views/layout/js/EventListener";
import {ParamsEncrypt} from "@lowcode/jpaas-share-component";
import {mapState} from 'pinia';
import userUser from "@/stores/userUser.js";
import useMain from "@/stores/useMain.js";
import useSystemConfig from "@/stores/useSystemConfig.js";
/*引入monaco相关语言及提示*/
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker'
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker'
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';

// import devicePixel from '@/assets/js/devicePixel.js'
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import ResourceApi from "@/common/api/user/resource";
window.monacoWorkConfig = {
    jsonWorker,
    cssWorker,
    htmlWorker,
    tsWorker,
    EditorWorker
}

import createRoutes from "@/views/layout/js/create-routes";

export default {
    provide() {
        return {
            /**
             * 组件模块映射，其他地方可以通过inject 注入使用
             */
            appModules: this.modules,
            /**
             * 广播频道，在应用中可以订阅广播.
             */
            broadCastChannel: this.broadChannel
        }
    },
    mixins: [EventListener, ParamsEncrypt,createRoutes],
    data() {
        return {
            locale:zhCN,
            theme: {
                token: {}

            },
            modules: import.meta.glob("@/views/**/*.vue"),
            broadChannel: new BroadcastChannel('broadCastChannel')
        }
    },
    computed: {
        ...mapState(userUser, ['siteName','user','menus']),
        ...mapState(useMain, ['menus']),
        ...mapState(useSystemConfig, ['systemHeme']),
        siteNameTmp() {
            let siteName = JSON.parse(window.localStorage.getItem("siteName") || "{}");
            return siteName;
        },
        language() {
            let language = window.localStorage.getItem("language");
            if (!language) {
                language = "zh-CN";
            }
            return language;
        }
    },
    mounted() {
        document.title = this.siteName[this.language] || this.siteNameTmp[this.language] || "敏捷开发平台";
        this.initLinkLog();
        // new devicePixel().init()
    },
    created() {
        window.name = "appHome";
        window['jpaas-base-url'] = import.meta.env.JPAAS_BASE_URL;
        this.init();
        this.setGlobalUser()
        this.initRoute();
    },
    methods: {
        /*
        * 刷新时没有路由的情况下 重定向路由；
        * */
        async initRoute(){
            const urlParams = new URLSearchParams(window.location.search);
            const params = Object.fromEntries(urlParams.entries());
            let {appId,appKey} = params;
            if((appId || appKey) && !this.$route.name && window.location.href.includes('webApp')){
                let path = window.location.pathname + window.location.search;
                this.$router.push({
                    path:'/',
                    query:{
                        redirectApp:path
                    }
                })
            }else if(appId && !this.$route.name && window.location.href.includes('microApp')){
                let path = window.location.pathname.split('/microApp')[1];
                path = `/microApp${path}`;
                this.$router.push({path,
                    query:{
                        appId
                    }
                })
            }
            else{
                let main = import.meta.env.JPAAS_BASE_URL;
                let indexName = `${main}`
                let pathname = window.location.pathname;
                if(indexName.replaceAll('/','') === pathname.replaceAll('/','')){
                    //默认进到首页
                    this.$router.push({name:'appHome'})
                }
            }
        },
        /*
        * 根据token获取当前登录人员信息;
        * */
        getCurUser(){
            ResourceApi.getCurUser().then(res=>{
                if(res.success){
                    window.curUser = res.data ;
                }
            })
        },
        /*
        * 把登录人员信息挂载到全局的window对象;
        * */
        setGlobalUser(){
            if(this.user){
                window.curUser = this.user ;
            }else {
                this.getCurUser()
            }
        },
        init() {
            this.broadChannel.postMessage("openMain")
            //进入的时候存一个缓存 表示main项目已经启动 给ac-admin项目监听 RightToolBar.vue
            window.addEventListener("beforeunload", () => {
                this.broadChannel.postMessage("closeMain")
            })
        },
        getFilePath(fileId) {
          return "/api/api-system/system/core/sysFile/public/download/"+ fileId;
        },
        initLinkLog(){
            let fileId = localStorage.getItem("linkLogoUrl");
            if(fileId) {
                const oldLink = document.head.querySelector("[rel='icon']");
                if(oldLink){
                      oldLink.href = this.getFilePath(fileId);
                }else {
                      const link = document.createElement('link');
                      link.rel = 'icon';
                      link.href = this.getFilePath(fileId);
                      document.head.appendChild(link);
                    }
            }
      }
    },

}
</script>
<style lang="less">
#app {
    height: 100%;
    width: 100%;
}
</style>
